package com.nwpu.hass.serviceimpl;
import com.nwpu.hass.domain.DeviceEntity;
import com.nwpu.hass.domain.RegisterformEntity;
import com.nwpu.hass.domain.UserEntity;
import com.nwpu.hass.domain.WarrantyEntity;
import com.nwpu.hass.repository.*;
import com.nwpu.hass.service.RedisService;
import com.nwpu.hass.service.RegisterformService;
import com.nwpu.hass.domain.*;
import com.nwpu.hass.exceptions.AuthorizeWechatException;
import com.nwpu.hass.repository.DeviceRepository;
import com.nwpu.hass.repository.RegisterformRepository;
import com.nwpu.hass.repository.UserRepository;
import com.nwpu.hass.repository.WarrantyRepository;
import com.nwpu.hass.service.UserService;
import com.nwpu.hass.utils.Status;
import com.nwpu.hass.utils.faceutils.GsonUtils;
import com.nwpu.hass.utils.faceutils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.*;

@Slf4j
@Service    //注入spring容器
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private DeviceRepository deviceRepository;

    @Resource
    private RegisterformRepository registerformRepository;

    @Resource
    private WarrantyRepository warrantyRepository;

    @Resource
    private MessageRepository messageRepository;

    @Resource
    private SystemMessageRepository systemMessageRepository;



    @Override
    public Long addUser(UserEntity userEntity) {
        return userRepository.save(userEntity).getUserid();
    }

    /**
     * 通过id查找对应的UserEntity
     * @param userId 用户id
     * @return 如果存在该用户，返回对应的UserEntity
     *         如果不存在，返回null
     */
    @Override
    public UserEntity getUserById(Long userId) {
        return userRepository.findUserEntityByUserid(userId);
    }

    /**
     * 通过用户名查找相应的UserEntity
     * @param username 用户名
     * @return 如果存在该用户，返回对应的UserEntity
     *         如果不存在，返回null
     */
    @Override
    public UserEntity getUserByUsername(String username) {
        return userRepository.findUserEntityByUsername(username);
    }

    @Override
    public void modifiedUser(UserEntity userEntity) {
        // 如果已经存在该id的用户，save会进行更新
        userRepository.save(userEntity);
    }

    private boolean canDelete(Long userId) {

        List<RegisterformEntity> registerformEntities = registerformRepository.findAllByBorrowPersonOrderByRecordDesc(userId);

        if (!Objects.isNull(registerformEntities) &&!registerformEntities.isEmpty()) {
            Set<Long> deviveIds = new HashSet<>();
            for(RegisterformEntity registerformEntity:registerformEntities){
                long possibleDevice = registerformEntity.getDevice();
                if(deviveIds.add(possibleDevice)){
                    DeviceEntity deviceEntity = deviceRepository.findDeviceEntityByDeviceId(possibleDevice);
                    if(deviceEntity.getStatus() == Status.BUSY.getStatus() ||
                            deviceEntity.getStatus() == Status.ONBORROW.getStatus() ||
                            deviceEntity.getStatus() == Status.ONRETURN.getStatus() ) {

                        if(registerformRepository.findAllByDeviceOrderByRecordDesc(deviceEntity.getDeviceId()).get(0).getBorrowPerson() == userId) {
                            return false;
                        }
                    }
                }
            }


        }

        List<WarrantyEntity> warrantyEntities = warrantyRepository.findAllByApplyPersonOrderByRecordDesc(userId);

        if (!Objects.isNull(warrantyEntities) &&!warrantyEntities.isEmpty()) {
            Set<Long> deviceIds = new HashSet<>();
            for(WarrantyEntity warrantyEntity:warrantyEntities){
                long possibleDevice = warrantyEntity.getDevice();
                if(deviceIds.add(possibleDevice)){
                    DeviceEntity deviceEntity = deviceRepository.findDeviceEntityByDeviceId(possibleDevice);
                    if(deviceEntity.getStatus() == Status.ONREPAIR.getStatus() ) {

                        if(warrantyRepository.findAllByDeviceOrderByRecordDesc(deviceEntity.getDeviceId()).get(0).getApplyPerson() == userId) {
                            return false;
                        }
                    }
                }
            }

        }

        return true;
    }

    @Override
    @Transactional
    public boolean deleteUser(UserEntity userEntity) {

        if(canDelete(userEntity.getUserid())) {
            warrantyRepository.deleteWarrantyEntitiesByApplyPerson(userEntity.getUserid());
            registerformRepository.deleteRegisterformEntitiesByBorrowPerson(userEntity.getUserid());
            messageRepository.deleteMessageEntitiesByUserid(userEntity.getUserid());
            userRepository.delete(userEntity);
            return true;
        }
        return false;
    }

    @Override
    public List<UserEntity> getAllUser(int min,int max) {
        return userRepository.findAllUser(min,max);
    }

    @Override
    public String getOpenId(String code) throws Exception {

        String url = "https://api.weixin.qq.com/sns/jscode2session";

        String openId_Information = HttpUtil.getOpenId(url, code);
        Auth4Wechat info = GsonUtils.fromJson(openId_Information,Auth4Wechat.class);
        String openId = info.getOpenid();

        if(null == openId){
            throw new AuthorizeWechatException("微信openId获取失败");
        }

        log.info("OPEN_ID: " + info.getOpenid());

        return openId;
    }

}
